﻿using System.Windows.Input;
using RialternativeSample.Client.Commanding;
using RialternativeSample.Client.Infrastructure;
using RialternativeSample.Server.Authorization.Models;
using RialternativeSample.Services.Interfaces;
using RialternativeSample.ViewModels.Interfaces;
using RialternativeSample.Views.Interfaces;

namespace RialternativeSample.ViewModels
{
    public class MainViewModel : Notifier, IMainViewModel
    {
        private IDialogService dialogService;

        public MainViewModel(IDialogService dialogService)
            : base()
        {
            this.dialogService = dialogService;
            this.LoginCommand = new RelayCommand<object>(o => this.Login());
            this.LogoutCommand = new RelayCommand<object>(o => this.Logout());
            WebContext.Current.Authentication.LoggedIn += (s, e) => this.RaisePropertyChanged(() => this.User);
            WebContext.Current.Authentication.LoggedOut += (s, e) => this.RaisePropertyChanged(() => this.User);
        }

        public ICommand LoginCommand { get; set; }

        public ICommand LogoutCommand { get; set; }

        public User User
        {
            get
            {
                return WebContext.Current.User;
            }
        }

        private void Login()
        {
            this.dialogService.ShowDialog(typeof(ILoginView));
        }

        private void Logout()
        {
            WebContext.Current.Authentication.Logout(logoutOperation =>
            {
                if (logoutOperation.HasError)
                {
                    // TODO
                }
            },
            null);
        }
    }
}
